package net.zhengxinyun.unifyApp.api.service;

import com.sirdc.modules.utils.StringUtils;
import net.zhengxinyun.unifyApp.api.entity.SysFile;
import net.zhengxinyun.unifyApp.api.mapper.SysFileMapper;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;


@Service
public class SysFileServiceImpl implements SysFileService {

    @Value("${file-upload}")
    private String filePath;

    @Value("${file-root}")
    private String fileroot;

    private SysFileMapper sysFileMapper;

    @Autowired
    public SysFileServiceImpl(SysFileMapper sysFileMapper) {
        this.sysFileMapper = sysFileMapper;
    }

    @Override
    public List<SysFile> query() {
        return sysFileMapper.selectAll();
    }


    @Override
    public HashMap<String,Object> save(MultipartFile file) {
        if (file.isEmpty()) {
            return null;
        }
        String oldName = file.getOriginalFilename();  // 文件名
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        //本地配置
//		String filePath = "D://temp-rainy//"; // 上传后的路径
        //服务器配置
//        String filePath = "//user//temp-rainy//";
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            return null;
        }
        String filename = "/temp-rainy/" + fileName;
        SysFile sysFile = new SysFile(fileName,suffixName,filename,oldName);
        int i = sysFileMapper.insert(sysFile);
        if (i == 0){
            return null;
        }
        HashMap<String,Object> map = new HashMap<>();
        map.put("fileId",sysFile.getId());
        map.put("fileUrl",filename);
        return map;
    }

    @Transactional
    public String delete(List<String> idList){
        for (String id:idList) {
            if (StringUtils.isBlank(id)){
                continue;
            }
            SysFile sysFile = sysFileMapper.selectByPrimaryKey(Long.valueOf(id));
            //本地配置
            String path = fileroot +sysFile.getUrl();
            //服务器配置
//            String path =sysFile.getUrl();
            File file = new File(path);
            if (file.exists()){
                if (!file.delete()){
                    return "删除本地图片失败";
                }
            }
            int i = sysFileMapper.deleteByPrimaryKey(Long.valueOf(id));
            if (i == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "文件删除失败";
            }
        }
        return "删除成功";
    }

    @Override
    public String downloadFile(HttpServletRequest request, HttpServletResponse response, String id) {
        SysFile sysFile = sysFileMapper.selectByPrimaryKey(Long.valueOf(id));
        String fileName = sysFile.getFileName();// 设置文件名，根据业务需要替换成要下载的文件名
        String name = sysFile.getOldName();
        if (fileName != null) {
            //设置文件路径
            String realPath = fileroot +sysFile.getUrl();
            File file = new File(realPath);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + name);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("success");
                } catch (Exception e) {
                    return "下载失败";
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载成功";
    }

    @Override
    public SysFile selectOne(Long id) {
        return sysFileMapper.selectByPrimaryKey(id);
    }




}
